'''XML parser'''

from xml_to_py.cc_input_section import InputSection
from xml_to_py.cc_output_section import OutputSection
from xml_to_py.cc_symbol import Symbol

import xml.etree.ElementTree as ET

def parseXML(filename):
    '''Parse a given XML file  and return a list of OutputSection objects'''
    sectionlist = []
    tree = ET.parse(filename)
    root = tree.getroot()

    for element in root.findall('output_section'):
        output_section = OutputSection()

        name = element.find('name').text
        output_section.setName(name)

        address = element.find('address').text
        output_section.setAddress(address)

        size = element.find('size').text
        output_section.setSize(size)

        isections = element.find('input_sections')
        for isection in isections.findall('input_section'):
            output_section.addInputSection(parseInputSection(isection))

        sectionlist.append(output_section)


def parseInputSection(xmlbranch):
    '''Parse part of XML describing the input section'''
    input_section = InputSection()

    name = xmlbranch.find('name').text
    input_section.setName(name)

    address = xmlbranch.find('address').text
    input_section.setAddress(address)

    size = xmlbranch.find('size').text
    input_section.setSize(size)

    origin = xmlbranch.find('origin').text
    input_section.setOrigin(origin)

    isections = xmlbranch.find('symbols')
    for sym in isections.findall('symbol'):
        input_section.addSymbol(parseSymbol(sym))

    return input_section


def parseSymbol(xmlbranch):
    '''Parse part of XML describing the input section'''
    symbol = Symbol()

    name = xmlbranch.find('name').text
    symbol.setName(name)

    address = xmlbranch.find('address').text
    symbol.setAddress(address)

    return symbol



